#include "t_cmd_bus.h"

Object_Command_Bus *command_bus_list = NULL;

void cmd_bus_register(Object_Command_Bus *cmd) {
    if (cmd) {
        cmd->next = command_bus_list;
        command_bus_list = cmd;
        BUS_LOG_DEBUG("Command '%s' registered", cmd->cmd_name);
    }
}

static Object_Command_Bus *find_command(const char *name) {
    for (Object_Command_Bus *cmd = command_bus_list; cmd != NULL; cmd = cmd->next) {
        if (strcasecmp(cmd->cmd_name, name) == 0) {
            return cmd;
        }
    }
    return NULL;
}

void cmd_bus_cb(const char *cmd, char *response, size_t buffer_size) {
    if (!cmd || !response) {
        snprintf(response, buffer_size, "cmd is null");
        return;
    }
    Object_Command_Bus *bus = find_command(cmd);
    if (!bus || !bus->bus_callback) {
        snprintf(response, buffer_size, "command not found");
        return;
    }
    if (!bus->bus_callback(bus->param, cmd, response, buffer_size) || response[0] == '\0') {
        snprintf(response, buffer_size, "callback failed or empty");
    }
    return;
}

size_t get_command_bus_list_length(void) {
    size_t count = 0;
    Object_Command_Bus *cmd = command_bus_list;
    while (cmd != NULL) {
        count++;
        cmd = cmd->next;
    }
    return count;
}
/*
// 自动注册函数收集，手动调用
extern void BUS_CMD_REG_help(void);
// 其他命令注册函数在这里添加

void register_all_commands(void) {
    BUS_CMD_REG_help();
    // 可扩展为注册更多命令
}
*/